<?php
/**
 *
 * @author 孙春雷
 *        
 */
/**
 * 计算期末库存
 *
 * @author scl
 *        
 */
class Controller_Balances extends Controller {
	
	/**
	 * 定义时间格式
	 *
	 * @var unknown
	 */
	const timefomat = 'Y-m-01';

	/**
	 * 每月统计期末的库存
	 */
	public function action_index()
	{
		// 定义开始时间和结束时间
		$endtime = date( self::timefomat );
		$date = date_create( $endtime );
		date_sub( $date, date_interval_create_from_date_string( '1 month' ) );
		$starttime = date_format( $date, self::timefomat );

		// 统计结存的数据
		$inventory = new Service_Inventory();
		$result = $inventory->balances( $starttime, $endtime );
		$current_out = $result ['current_out'];
		$closing = $result ['closing'];
		
		// 更新本期出的成本
		$delivery = new Model_Deliveryorders();
		foreach ( $current_out as $key => $value )
		{
			if ($value ['count'])
			{
				$cost = $value ['cost'] / $value ['count'];
				$delivery->modifyCost( $cost, $key, $starttime, $endtime );
			}
		}
		
		// 添加期末库存到库存表
		$inventory = new Model_Inventories();
		foreach ( $closing as $key => $value )
		{
			$sku_info = Deliverycheck::load_sku_info( $key );
			$arr_inventory = array (
					Model_Inventories::sku => $key,
					Model_Inventories::sku_name => $sku_info ['products_name_cn'],
					Model_Inventories::sku_standard => $sku_info ['size'],
					Model_Inventories::storage_position => $sku_info ['products_place'],
					Model_Inventories::quantity => $value ['count'],
					Model_Inventories::cost => $value ['cost'],
					Model_Inventories::inventory_date => date( self::timefomat ) 
			);
			$id = $inventory->get_id( $key, date( self::timefomat ) );
			if ($id)
			{
				$inventory->modify( $id, $arr_inventory );
			}
			else
			{
				$inventory->add( $arr_inventory );
			}
		}
		echo "执行的库存成本数据是".$starttime."--".$endtime;
		echo '期末库存执行完毕'.date(Y-m-d H:i:s);
	}
}
